package question.solution368;

import question.SolutionTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution368 implements SolutionTemplate {

    public List<Integer> largestDivisibleSubset(int[] nums) {
        List<Integer> result = new ArrayList<>();

        if(nums.length ==1){
            result.add(nums[0]);
            return result;
        }
        Arrays.sort(nums);
        int dpAllMax = 1;
        int maxIndex = 0;
        int[] dp = new int[nums.length];
        dp[0] = 1;

        for(int i=1;i<nums.length;i++){
            int dpMax = 0;
            for(int j = i; j >=0 ; j--) {
                if(nums[i]%nums[j]==0 && dp[j]>dpMax){
                    dpMax = dp[j];
                }
            }
            dp[i] = dpMax+1;
            if(dp[i] > dpAllMax){
                dpAllMax = dp[i];
                maxIndex = i;
            }
        }
        result.add(nums[maxIndex]);
        for(int i=maxIndex, j=i-1, currentDp = dpAllMax-1;currentDp>0;){
            if(nums[i]%nums[j] == 0 && dp[j] == currentDp){
                result.add(nums[j]);
                i=j;
                currentDp--;
            }
            j--;
        }
        return result;
    }

    public void test() {
        int[] arr = {3,17};
        List<Integer> result = largestDivisibleSubset(arr);
        return;
    }
}
